// packageRecruit/pages/work-job-detail/work-job-detail.js
import {
    workDetailEcho,
    workStatusManage,
    jobOffShelf
} from '../../api/recruit'
import {
    toast,
    confirm,
    getLocation,
    createQrcode,
    base64ToWxfile
} from '../../../utils/util'
import user from '../../../utils/user'
const app = getApp()
import {
    getSystemSetUp,
    createClientQrCode
} from '../../../api/app.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        jobId: '',
        workInfo: {},
        workLongitude: '',
        workLatitude: '',
        distance: '',
        isPoster: false,
        code: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    async onLoad(options) {
        console.log(options, 'options')

        this.setData({
            jobId: options.jobid
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /** ,
     * 生命周期函数--监听页面显示
     */
    async onShow() {
        await user.waitLogin()
        await this.createInviteQrCode()
        this.getWorkDetailEcho()
        this.currentLocation()
    },

    createInviteQrCode() {
        return new Promise(async resolve => {
            const result = await getSystemSetUp({})
            this.setData({
                isNeedAuthSalaryCard: result.isNeedAuthSalaryCard
            })
            let scene = ''
            scene = 'id=' + this.data.jobId + '&uid=' + user.userId + '&force=' + (!this.data.isNeedAuthSalaryCard ? 0 : 1) + '&tJ=1'
            console.log(scene, '')
            const text = app.globalData.qrCodeUrl + '?qrcodeType=normal&scene=' + encodeURIComponent(scene)
            console.log(111, text)
            const myqrCode = await createQrcode('qrcode', text)
            this.setData({
                code: myqrCode
            })
            createClientQrCode({
                page: 'pages/job-detail/job-detail',
                width: 100,
                scene: scene,
            }).then(res => {
                this.setData({
                    ['enterprise.qrId']: res.qrId,
                    qrId: res.qrId
                })
                let qrCode = res // 后台返回的base64图片流
                console.log(3333, qrCode)
                base64ToWxfile(qrCode, Math.ceil(Math.random() * 10000000000) + '.png').then(path => {
                    this.setData({
                        qrcode: path
                    }, () => {})
                    resolve()
                })
            })
        })
    },
    // 分享
    onShare() {
        this.setData({
            isPoster: true
        })
    },

    // 进报名记录
    goWorkDetail(event) {
        wx.navigateTo({
            url: '/packageRecruit/pages/work-job-browse-detail/work-job-browse-detail?id=' + this.data.jobId,
        })
    },
    // 海报取消按钮回调
    onCloseShare() {
        this.setData({
            isPoster: false
        })
    },
    // 海报保存按钮回调
    onPreservation(event) {
        wx.saveImageToPhotosAlbum({
            filePath: event.detail,
            success(res) {
                app.toast('成功保存', 'success')
            },
            fail(rej) {
                app.toast('保存失败')
            }
        })
    },
    // 获取岗位信息
    getWorkDetailEcho() {
        workDetailEcho({
            jobId: this.data.jobId
        }).then(res => {

            res.jobDetail = res.jobDetail.replace(/[\r\n]/g, '「').split('「')
            res.jobTag = res.jobTag.split(';')
            if (res.jobTag.length === 1 && !res.jobTag[0]) {
                res.jobTag = []
            }
            // ['info.template']:this.data.text.replace(/#[1-9|\u4e00-\u9fa5|A-Z|a-z]{1,}/g,function(word){
            //     return '<span style="color:#3E5FF5">' + word + '</span>'
            // })
            // 吧多分割的 字符串 去除
            res.jobDetail = res.jobDetail.filter(item => item !== '')
            res.jobDetailRich = res.jobDetail.map(item => {
                return item.replace(/#[1-9|\u4e00-\u9fa5|A-Z|a-z]{1,}/g, function (word) {
                    return '' // '<span style="color:#3E5FF5">' + word + '</span>'
                })
            })
            this.setData({
                workInfo: res,
                workLongitude: Number(res.jobLocation.split(',')[0]),
                workLatitude: Number(res.jobLocation.split(',')[1])
            })
            // const c = new jobCanvas(this.data.workInfo, this.data.qrcode)

        })
    },
    onPreview(event) {
        const {
            url
        } = event.currentTarget.dataset
        wx.previewImage({
            urls: [url]
        })
    },
    onPlay(event) {
        // 获取 video 上下文 videoContext 对象
        this.videoContext = wx.createVideoContext(event.currentTarget.id, this)
        // 进入全屏状态
        this.videoContext.requestFullScreen()
        return 0
    },
    // 调用导航
    onNavigation() {
        wx.openLocation({
            longitude: this.data.workLongitude,
            latitude: this.data.workLatitude
            // name: this.positionDetailsList.jobAddress,
            // address: this.positionDetailsList.jobAddressDetail
        })
    },
    // 上下架
    setWorkStatusManage() {
        confirm(('确定' + (this.data.workInfo.jobState ? '下架' : '上架') + '吗!')).then(res => {
            workStatusManage({
                id: this.data.jobId,
                jobState: this.data.workInfo.jobState == '1' ? '0' : '1'
            }).then(async () => {
                await toast(((this.data.workInfo.jobState ? '下架' : '上架') + '成功'))
                setTimeout(async () => {
                    await this.getWorkDetailEcho()
                }, 500)
            })
        })
    },
    // 去编辑
    goWorkEdit() {
        wx.navigateTo({
            url: '/packageRecruit/pages/create-basic-info/create-basic-info?type=edit&jobid=' + this.data.jobId,
        })
    },
    // 岗位删除
    onJobOffShelf() {
        confirm('确定删除吗？').then(res => {
            jobOffShelf({
                id: this.data.workInfo.id
            }).then(async () => {
                await toast('删除成功')
                setTimeout(async () => {
                    wx.redirectTo({
                        url: '/packageRecruit/pages/work-job/work-job'
                    })
                }, 500)
            })
        })

    },
    // 三个点更多
    onOperation(event) {
        wx.showActionSheet({
            itemList: ['删除', this.data.workInfo.jobState ? '下架' : '上架'],
            success: (res) => {
                const {
                    tapIndex
                } = res
                if (tapIndex === 1) {
                    this.setWorkStatusManage(this.data.workInfo.jobState ? 0 : 1)
                }
                if (tapIndex === 0) {
                    this.onJobOffShelf()
                }
            }
        })
    },
    // 计算现在位置到公司位置之间的距离
    currentLocation() {
        getLocation().then(res => {
            // 计算当前位置和公司位置，之间的距离
            var La1 = (res.latitude * Math.PI) / 180.0
            var La2 = (this.data.workLatitude * Math.PI) / 180.0
            var La3 = La1 - La2
            var Lb3 =
                (res.longitude * Math.PI) / 180.0 -
                (this.data.workLongitude * Math.PI) /
                180.0
            var s =
                2 *
                Math.asin(
                    Math.sqrt(
                        Math.pow(Math.sin(La3 / 2), 2) +
                        Math.cos(La1) *
                        Math.cos(La2) *
                        Math.pow(Math.sin(Lb3 / 2), 2)
                    )
                )
            s = s * 6378.137 // 地球半径
            s = Math.round(s * 10000) / 10000
            this.setData({
                distance: parseInt(s)
            })
        })
    },
})